<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            #result {
                width: 400px;
                height: 300px;
                border: solid 1px #666;
            }
        </style>
    </head>
    <body>
        <a href="/home">Home</a>
        <a href="/about">About</a>
        <hr />
        <div id="result"></div>

        <script>
            //获取所有的 a 元素
            let links = document.querySelectorAll("a");
            //遍历
            links.forEach((item) => {
                //绑定事件
                item.addEventListener("click", function (e) {
                    //阻止默认行为
                    e.preventDefault();
                    // pushState
                    history.pushState({ id: 200 }, null, this.href);
                    //根据 路径显示不同的内容
                    let pathname = window.location.pathname; // hash
                    //判断
                    switch (pathname) {
                        case "/home":
                            result.innerHTML = "首页";
                            break;
                        case "/about":
                            result.innerHTML = "关于我们";
                            break;
                        default:
                            result.innerHTML = "404 找不到";
                    }
                });
            });

            //当弹出历史状态时, 触发该事件
            window.addEventListener("popstate", function (e) {
                console.log(e);
                //根据 路径显示不同的内容
                let pathname = window.location.pathname; // hash
                //判断
                switch (pathname) {
                    case "/home":
                        result.innerHTML = "首页";
                        break;
                    case "/about":
                        result.innerHTML = "关于我们";
                        break;
                    default:
                        result.innerHTML = "404 找不到";
                }
            });
        </script>
    </body>
</html>
